<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限
if (!$current_user) {
    header('Location: /POS/login.php');
    exit;
}

// 处理操作
$action = $_GET['action'] ?? '';
$member_id = $_GET['id'] ?? 0;

// 处理会员添加
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';
    $balance = isset($_POST['balance']) ? floatval($_POST['balance']) : 0;
    $points = isset($_POST['points']) ? intval($_POST['points']) : 0;
    
    // 验证手机号是否已存在
    $check_sql = "SELECT id FROM users WHERE phone = ?";
    $existing_member = Database::fetch($check_sql, [$phone]);
    
    if ($existing_member) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该手机号已被注册'
        ];
    } else {
        // 插入新会员
        $sql = "INSERT INTO users (name, phone, email, balance, points, created_at, role) VALUES (?, ?, ?, ?, ?, NOW(), 'member')";
        $result = Database::query($sql, [$name, $phone, $email, $balance, $points]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '会员添加成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '会员添加失败'
            ];
        }
    }
    
    // 重定向到会员列表
    header('Location: /POS/members.php');
    exit;
}

// 处理会员编辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'edit' && $member_id) {
    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $balance = isset($_POST['balance']) ? floatval($_POST['balance']) : 0;
    $points = isset($_POST['points']) ? intval($_POST['points']) : 0;
    
    // 检查手机号是否被其他会员使用
    $check_sql = "SELECT id FROM users WHERE phone = ? AND id != ?";
    $existing_member = Database::fetch($check_sql, [$phone, $member_id]);
    
    if ($existing_member) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该手机号已被其他会员使用'
        ];
    } else {
        // 更新会员信息
        $sql = "UPDATE users SET name = ?, phone = ?, balance = ?, points = ? WHERE id = ?";
        $result = Database::query($sql, [$name, $phone, $balance, $points, $member_id]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '会员信息更新成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '会员信息更新失败'
            ];
        }
    }
    
    // 重定向到会员列表
    header('Location: /POS/members.php');
    exit;
}

// 处理会员余额充值
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'recharge' && $member_id) {
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    
    if ($amount <= 0) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '充值金额必须大于0'
        ];
    } else {
        // 更新会员余额
        $sql = "UPDATE users SET balance = balance + ? WHERE id = ?";
        $result = Database::query($sql, [$amount, $member_id]);
        
        if ($result) {
            // 记录充值记录
            $sql = "INSERT INTO member_transactions (member_id, amount, type, description, created_at) 
                    VALUES (?, ?, 'recharge', '会员充值', NOW())";
            Database::query($sql, [$member_id, $amount]);
            
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '充值成功，余额已更新'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '充值失败'
            ];
        }
    }
    
    // 重定向到会员列表
    header('Location: /POS/members.php');
    exit;
}

// 处理会员删除
if ($action === 'delete' && $member_id && $current_user['role'] === 'admin') {
    // 检查会员是否有关联订单
    $check_sql = "SELECT COUNT(*) FROM orders WHERE user_id = ?";
    $order_count = Database::fetchColumn($check_sql, [$member_id]);
    
    if ($order_count > 0) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该会员有关联订单，无法删除'
        ];
    } else {
        // 删除会员
        $sql = "DELETE FROM users WHERE id = ? AND role = 'member'";
        $result = Database::query($sql, [$member_id]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '会员删除成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '会员删除失败'
            ];
        }
    }
    
    // 重定向到会员列表
    header('Location: /POS/members.php');
    exit;
}

// 查询单个会员信息（用于编辑）
$member = null;
if ($action === 'edit' && $member_id) {
    $sql = "SELECT * FROM users WHERE id = ? AND role = 'member'";
    $member = Database::fetch($sql, [$member_id]);
    
    if (!$member) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '会员不存在'
        ];
        header('Location: /POS/members.php');
        exit;
    }
}

// 获取会员列表
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 构建查询条件
$where = ["role = 'member'"];
$params = [];

if ($search) {
    $where[] = "(name LIKE ? OR phone LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// 查询会员总数
$count_sql = "SELECT COUNT(*) FROM users $where_clause";
$total = Database::fetchColumn($count_sql, $params);
$total_pages = ceil($total / $per_page);

// 查询会员列表
$sql = "SELECT * FROM users $where_clause ORDER BY created_at DESC LIMIT $offset, $per_page";
$members = Database::fetchAll($sql, $params);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">会员管理</h1>
            <p class="text-muted">查看和管理所有会员信息</p>
        </div>
        <div class="col-md-6 text-md-right">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addMemberModal">
                <i class="fas fa-plus-circle"></i> 添加会员
            </button>
        </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <form action="" method="GET" class="row">
                <div class="col-md-8 mb-3 mb-md-0">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" name="search" placeholder="会员姓名/手机号/邮箱" value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary btn-block">搜索</button>
                </div>
                <div class="col-md-2">
                    <a href="/POS/members.php" class="btn btn-secondary btn-block">重置</a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 会员列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>姓名</th>
                            <th>手机号</th>
                            <th>邮箱</th>
                            <th>余额</th>
                            <th>积分</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($members)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">没有找到相关会员</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($members as $m): ?>
                        <tr>
                            <td><?php echo $m['id']; ?></td>
                            <td><?php echo htmlspecialchars($m['name']); ?></td>
                            <td><?php echo htmlspecialchars($m['phone']); ?></td>
                            <td><?php echo htmlspecialchars($m['email'] ?? '-'); ?></td>
                            <td><?php echo number_format($m['balance'], 2); ?> 元</td>
                            <td><?php echo $m['points']; ?></td>
                            <td><?php echo date('Y-m-d H:i', strtotime($m['created_at'])); ?></td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#rechargeModal<?php echo $m['id']; ?>">
                                        <i class="fas fa-wallet"></i>
                                    </button>
                                    <a href="/POS/members.php?action=edit&id=<?php echo $m['id']; ?>" class="btn btn-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if ($current_user['role'] === 'admin'): ?>
                                    <a href="#" onclick="confirmDelete(<?php echo $m['id']; ?>); return false;" class="btn btn-danger">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- 充值模态框 -->
                                <div class="modal fade" id="rechargeModal<?php echo $m['id']; ?>" tabindex="-1" role="dialog" aria-hidden="true">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <form action="/POS/members.php?action=recharge&id=<?php echo $m['id']; ?>" method="POST">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">会员充值 - <?php echo htmlspecialchars($m['name']); ?></h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="form-group">
                                                        <label>当前余额</label>
                                                        <input type="text" class="form-control" value="<?php echo number_format($m['balance'], 2); ?> 元" readonly>
                                                    </div>
                                                    <div class="form-group">
                                                        <label>充值金额</label>
                                                        <div class="input-group">
                                                            <div class="input-group-prepend">
                                                                <span class="input-group-text">¥</span>
                                                            </div>
                                                            <input type="number" class="form-control" name="amount" min="0.01" step="0.01" required>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                                    <button type="submit" class="btn btn-primary">确认充值</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 添加会员模态框 -->
<div class="modal fade" id="addMemberModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="/POS/members.php?action=add" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">添加新会员</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>姓名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="form-group">
                        <label>手机号 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="phone" required>
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" class="form-control" name="email">
                    </div>
                    <div class="form-group">
                        <label>初始余额</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">¥</span>
                            </div>
                            <input type="number" class="form-control" name="balance" min="0" step="0.01" value="0">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>初始积分</label>
                        <input type="number" class="form-control" name="points" min="0" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑会员表单 -->
<?php if ($action === 'edit' && $member): ?>
<div class="container-fluid mt-4">
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">编辑会员信息</h5>
        </div>
        <div class="card-body">
            <form action="/POS/members.php?action=edit&id=<?php echo $member['id']; ?>" method="POST">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>姓名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($member['name']); ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>手机号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($member['phone']); ?>" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>余额</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">¥</span>
                                </div>
                                <input type="number" class="form-control" name="balance" min="0" step="0.01" value="<?php echo htmlspecialchars($member['balance']); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>积分</label>
                            <input type="number" class="form-control" name="points" min="0" value="<?php echo htmlspecialchars($member['points']); ?>">
                        </div>
                    </div>
                </div>
                <div class="form-group mt-3">
                    <a href="/POS/members.php" class="btn btn-secondary">返回列表</a>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// 删除确认
function confirmDelete(memberId) {
    if (confirm('确定要删除此会员吗？此操作不可恢复！')) {
        window.location.href = '/POS/members.php?action=delete&id=' + memberId;
    }
}

// 显示提示消息
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['alert'])): ?>
    showAlert('<?php echo $_SESSION['alert']['message']; ?>', '<?php echo $_SESSION['alert']['type']; ?>');
    <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 